"use strict";
import path from "path";
import { app, protocol, BrowserWindow, dialog } from "electron";
import { createProtocol } from "vue-cli-plugin-electron-builder/lib";
import installExtension, { VUEJS_DEVTOOLS } from "electron-devtools-installer";
import dayjs from "dayjs";
import { time } from "console";
const isDevelopment = process.env.NODE_ENV !== "production";
const fs = require("fs");
var SMB2 = require("smb2");
global.Promise = require("bluebird");
var outHOST;
const { ipcMain } = require("electron");

// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
  { scheme: "app", privileges: { secure: true, standard: true } },
]);
var win = null;
async function createWindow() {
  // Create the browser window.
  win = new BrowserWindow({
    width: 1920,
    height: 1080,
    show: false, // 先隐藏
    webPreferences: {
      // Use pluginOptions.nodeIntegration, leave this alone
      // See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
      nodeIntegration: true,
      preload: path.join(__dirname, "preload.js"),
      // contextIsolation: !process.env.ELECTRON_NODE_INTEGRATION
    },
  });

  win.on("ready-to-show", function () {
    win.show(); // 初始化后再显示
  });
  win.setMenuBarVisibility(false);

  if (process.env.WEBPACK_DEV_SERVER_URL) {
    // Load the url of the dev server if in development mode
    await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL);
    if (!process.env.IS_TEST) {
      win.webContents.openDevTools();
    }
  } else {
    createProtocol("app");
    // Load the index.html when not in development
    win.loadURL("app://./index.html");
  }
}

// Quit when all windows are closed.
app.on("window-all-closed", () => {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== "darwin") {
    app.quit();
  }
});

app.on("activate", () => {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (BrowserWindow.getAllWindows().length === 0) createWindow();
});

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on("ready", async () => {
  if (isDevelopment && !process.env.IS_TEST) {
    // Install Vue Devtools
    try {
      await installExtension(VUEJS_DEVTOOLS);
    } catch (e) {
      console.error("Vue Devtools failed to install:", e.toString());
    }
  }
  createWindow();
});
app.setAppUserModelId("体系监测软件");
app.setName("体系监测软件");

// Exit cleanly on request from parent process in development mode.
if (isDevelopment) {
  if (process.platform === "win32") {
    process.on("message", (data) => {
      if (data === "graceful-exit") {
        app.quit();
      }
    });
  } else {
    process.on("SIGTERM", () => {
      app.quit();
    });
  }
}

// 作为客户端



// Laser_Value_

//LED_CloseLED LED_OpenLED

ipcMain.on("connectServer", function (event, message) {
  //开启激光

  outHOST = String(message).trim();
  connectMSSql(event);
});

ipcMain.on("disConnectServer", function (event, message) {
  //开启激光

  if (pool != null) {
    pool.close();
    pool = null;
    request = null;
  }
});

//拉曼光谱仪

ipcMain.on("getRamanResults", function (event, e) {
  //拉取拉曼测试结果

  // if (client == null) return;
  if (e == "history") {
    getHistory(event);

    return;
  }


  getCurrent(event)

});




ipcMain.on("getPHResults", function (event, e) {
  //拉取拉曼测试结果

  // if (client == null) return;
  if (e == "history") {
    getHistory_PH(event);

    return;
  }

  if (e == "tenminutes") {
    getHistory_PH_tenMinutes(event);

    return;
  }

  getCurrent_PH(event)

});
//Server=localhost\SQLEXPRESS;Database=master;Trusted_Connection=True;
const sqlTcpIp = require("mssql");
let request = null;

let pool = null;
function connectMSSql(event) {
  const config = {
    server:
      process.env.NODE_ENV == "production"
        ? `${outHOST.split(":")[0]}`
        : "localhost",

    database: "MPDataBase",

    user: process.env.NODE_ENV == "production"
    ?"zjucoer":"raman",

    password: process.env.NODE_ENV == "production"?"zjucoer":"coer",
    options: {
      trustedConnection: true,
      encrypt: false,
      enableArithAbort: true,
      trustServerCertificate: true,
    },
  };
  pool = new sqlTcpIp.ConnectionPool(config);

  pool.connect().then(
    () => {
      //console.log("连接成功1");
      request = new sqlTcpIp.Request(pool);
      event.reply("connect_reply", "S");
    },
    (e) => {
      event.reply("connect_reply", "F");
      //console.log("连接失败");
      //console.log(e);
      // dialog.showErrorBox('错误',e.toString())
    }
  );

  pool.on("error", (err) => {
    event.reply("connect_reply", "F");
    //console.log("error: ", err);
  });
}

function getHistory(event) {
  //console.log("getHistory");
  if (request == null) {
    return
    };
  request.query(
    "SELECT  [id],[time],[c_MethylPropionate],[c_Methanol],[c_SWJLpt],[c_YESEJZ] FROM [MPDataBase].[dbo].[NewMPRamanDataResult] WHERE time >= DATEADD(DAY, -30, GETDATE())",
    (err, recordset) => {
      //console.log(recordset.recordset);
      if (err) {
        event.reply("connect_reply", "DF");
        //console.log(err);
       // dialog.showErrorBox("失败1", err.toString());
      }
      event.reply("RamanDataResultsHistory_reply", recordset.recordset);
    }
  );
}

function getCurrent(event) {
  //console.log("getCurrent");
  if (request == null) {
  return
  };
  request.query(
    "SELECT TOP (1)  [id],[time],[c_MethylPropionate],[c_Methanol],[c_SWJLpt],[c_YESEJZ] FROM [MPDataBase].[dbo].[NewMPRamanDataResult] ORDER BY id DESC",
    (err, recordset) => {
     // console.log(recordset.recordset);
      if (err) {
        event.reply("connect_reply", "DF");
       // console.log(err);
        //dialog.showErrorBox("失败2", err.toString());
      }
      event.reply("RamanDataResults_reply", recordset.recordset);
    }
  );
}



function getCurrent_PH(event) {
  //console.log("getCurrent");
  if (request == null) {
  return
  };
  request.query(
    "SELECT TOP (1)  [id],[time],[pH_data] FROM [MPDataBase].[dbo].[pHDataResult] ORDER BY id DESC ",
    (err, recordset) => {
     // console.log(recordset.recordset);
      if (err) {
        event.reply("connect_reply", "DF");
       // console.log(err);
       // dialog.showErrorBox("失败3", "数据读取失败");
      }
      event.reply("ph_reply", recordset.recordset);
    }
  );
}


function getHistory_PH(event) {
  //console.log("getCurrent");
  if (request == null) {
  return
  };
  request.query(
    "SELECT  [id],[time],[pH_data] FROM [MPDataBase].[dbo].[pHDataResult]  WHERE time >= DATEADD(DAY, -30, GETDATE())",
    (err, recordset) => {
     // console.log(recordset.recordset);
      if (err) {
       // console.log(err);
       event.reply("connect_reply", "DF");
       // dialog.showErrorBox("失败4", "数据读取失败");
      }
      event.reply("phHistory_reply", recordset.recordset);
    }
  );
}


function getHistory_PH_tenMinutes(event) {
  //console.log("getCurrent");
  if (request == null) {
  return
  };
  request.query(
    "SELECT [id],[time],[pH_data] FROM [MPDataBase].[dbo].[pHDataResult] WHERE time >= DATEADD(minute, -10, GETDATE())",
    (err, recordset) => {
     // console.log(recordset.recordset);
      if (err) {
        event.reply("connect_reply", "DF");
       // console.log(err);
        //dialog.showErrorBox("失败5", "数据读取失败");
      }
      event.reply("ph_reply_tenMinutes", recordset.recordset);
    }
  );
}



//C2H4的backgroundJs

const DbClient = require('ali-mysql-client');

let db_CO; let db_C2H4;




function initMysqlClient_CO(ipStr) {
  if(isDevelopment){
    db_CO = new DbClient({
      // host: '192.168.2.152',
      host: ipStr,
  
      port: '3306',
      user: 'root',
      password: 'Core1234!@#$',
      database: 'data'
  });
  }else{
    db_CO = new DbClient({
      // host: '192.168.2.152',
      host: ipStr,
  
      port: '3306',
      user: 'root',
      password: '123456',
      database: 'data'
  });
  }
}


function initMysqlClient_C2H4(ipStr) {
  if(isDevelopment){
    db_C2H4 = new DbClient({
      // host: '192.168.2.152',
      host: ipStr,
  
      port: '3306',
      user: 'root',
      password: 'Core1234!@#$',
      database: 'data'
  });
  }
  else{
    db_C2H4 = new DbClient({
      // host: '192.168.2.152',
      host: ipStr,
  
      port: '3306',
      user: 'root',
      password: '123456',
      database: 'data'
  });
  }
}


// 作为客户端


// Laser_Value_

//LED_CloseLED LED_OpenLED

ipcMain.on("connectServer_coc2h4", function (event, message) {

  console.log(message)
if(message.address_CO){
  initMysqlClient_CO(message.address_CO);

}

if(message.address_C2H4){

  initMysqlClient_C2H4(message.address_C2H4);
}
  
  //开启激光

 // outHOST = String(message).trim();
});

ipcMain.on("disConnectServer_coc2h4", function (event, message) {
  //开启激光
  if(message.address_CO){
    db_CO = null;

  
  }
  
  if(message.address_C2H4){
  
    db_C2H4 = null;

  }
});

//拉曼光谱仪

ipcMain.on("getCOResults", function (event, e) {
  //拉取拉曼测试结果

  // if (client == null) return;
  if (e == "history") {
    getHistory_CO(event);

    return;
  }


  getCurrent_CO(event)

});







async function getCurrent_CO(event) {

  db_CO.sql('select * from co ORDER BY id desc limit 1')
  .execute().then(result => {
  

  event.reply("CODataResults_reply", result);
    
  }
  ).catch(err => {
    dialog.showErrorBox("getCurrent_CO", err.toString());
    event.reply("connect_reply_CO", "DF");
  })




}

async function getHistory_CO(event) {

 db_CO.sql(`select * from co where STR_TO_DATE(date_str,'%Y/%m/%d %H:%i') > DATE_SUB(CURDATE(), INTERVAL 3 MONTH)`)
  .execute().then(result => {
  event.reply("CODataResultsHistory_reply", result);
  }
  ).catch(err => {
    dialog.showErrorBox("getHistory_CO", err.toString());
    event.reply("connect_reply_CO", "DF");
  })
}


ipcMain.on("getC2H4Results", function (event, e) {
  //拉取拉曼测试结果

  // if (client == null) return;
  if (e == "history") {
   
    getHistory_C2H4(event);

    return;
  }


  getCurrent_C2H4(event)

});


async function getCurrent_C2H4(event) {

db_C2H4.sql('select * from c2h4 ORDER BY id desc limit 1')
  .execute().then(result => {
 
  event.reply("C2H4DataResults_reply", result);
  }
  ).catch(err => {
    event.reply("connect_reply_C2H4", "DF");
  })

}

async function getHistory_C2H4(event) {
 db_C2H4.sql(`select * from c2h4 where STR_TO_DATE(date_str,'%Y/%m/%d %H:%i') > DATE_SUB(CURDATE(), INTERVAL 3 MONTH)`)
  .execute().then(result => {
 

  event.reply("C2H4DataResultsHistory_reply", result);
  }).catch(err => {
    event.reply("connect_reply_C2H4", "DF");
  })

}


